package com.campusbook.dao;

import com.campusbook.model.Book;
import org.apache.ibatis.annotations.*;
import java.util.List;

@Mapper
public interface BookDao {
    
    @Select("SELECT b.*, bc.name as categoryName, u.full_name as ownerName " +
            "FROM books b " +
            "LEFT JOIN book_categories bc ON b.category_id = bc.id " +
            "LEFT JOIN users u ON b.owner_id = u.id " +
            "WHERE b.id = #{id}")
    Book findById(Long id);
    
    @Select("SELECT b.*, bc.name as categoryName, u.full_name as ownerName " +
            "FROM books b " +
            "LEFT JOIN book_categories bc ON b.category_id = bc.id " +
            "LEFT JOIN users u ON b.owner_id = u.id " +
            "WHERE b.status = 'AVAILABLE'")
    List<Book> findAvailableBooks();
    
    @Select("SELECT b.*, bc.name as categoryName, u.full_name as ownerName " +
            "FROM books b " +
            "LEFT JOIN book_categories bc ON b.category_id = bc.id " +
            "LEFT JOIN users u ON b.owner_id = u.id " +
            "WHERE b.owner_id = #{ownerId}")
    List<Book> findByOwnerId(Long ownerId);
    
    @Insert("INSERT INTO books(title, author, isbn, category_id, description, cover_image, owner_id, status, condition, location) " +
            "VALUES(#{title}, #{author}, #{isbn}, #{categoryId}, #{description}, #{coverImage}, #{ownerId}, #{status}, #{condition}, #{location})")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    void save(Book book);
    
    @Update("UPDATE books SET title=#{title}, author=#{author}, isbn=#{isbn}, category_id=#{categoryId}, " +
            "description=#{description}, cover_image=#{coverImage}, status=#{status}, condition=#{condition}, " +
            "location=#{location}, updated_at=NOW() WHERE id=#{id}")
    void update(Book book);
    
    @Delete("DELETE FROM books WHERE id = #{id}")
    void delete(Long id);
    
    @Update("UPDATE books SET status=#{status}, updated_at=NOW() WHERE id=#{id}")
    void updateStatus(@Param("id") Long id, @Param("status") String status);
}
